//
//  YCFunctionView.m
//  DemoFunctionView
//
//  Created by 唐可雄 on 16/6/21.
//  Copyright © 2016年 swustyc. All rights reserved.
//

#import "YCFunctionView.h"

#pragma mark - YCFunctionViewCell

@implementation YCFunctionViewCell

#pragma mark - Life Cycle

- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (newSuperview) {
        [self addSubviews];
    }
    
    [super willMoveToSuperview:newSuperview];
}

#pragma mark - Setter and Getter

- (UIImageView *)imgView {
    if (!_imgView) {
        _imgView = [[UIImageView alloc] init];
    }
    
    return _imgView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont systemFontOfSize:15.f];
    }
    
    return _titleLabel;
}

- (UILabel *)badgeLabel {
    if (!_badgeLabel) {
        _badgeLabel = [[UILabel alloc] init];
    }
    
    return _badgeLabel;
}

#pragma mark - View Config 

- (void)addSubviews {
    [self addImgView];
    [self addTitleLabel];
    [self addBadgeLabel];
}

- (void)addImgView {
    self.imgView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.imgView];
    
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.imgView
                                                     attribute:NSLayoutAttributeTop
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self.contentView
                                                     attribute:NSLayoutAttributeTop
                                                    multiplier:1.0f
                                                      constant:0.f]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.imgView
                                                     attribute:NSLayoutAttributeLeading
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self.contentView
                                                     attribute:NSLayoutAttributeLeading
                                                    multiplier:1.0f
                                                      constant:8.f]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.imgView
                                                     attribute:NSLayoutAttributeTrailing
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self.contentView
                                                     attribute:NSLayoutAttributeTrailing
                                                    multiplier:1.0f
                                                      constant:-8.f]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.imgView
                                                     attribute:NSLayoutAttributeHeight
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self.contentView
                                                     attribute:NSLayoutAttributeWidth
                                                    multiplier:1.0f
                                                      constant:-16.f]];
}

- (void)addTitleLabel {
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.titleLabel];
    
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.titleLabel
                                                     attribute:NSLayoutAttributeTop
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self.imgView
                                                     attribute:NSLayoutAttributeBottom
                                                    multiplier:1.0f
                                                      constant:0.f]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.titleLabel
                                                     attribute:NSLayoutAttributeLeading
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self.contentView
                                                     attribute:NSLayoutAttributeLeading
                                                    multiplier:1.0f
                                                      constant:0.f]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.titleLabel
                                                     attribute:NSLayoutAttributeTrailing
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self.contentView
                                                     attribute:NSLayoutAttributeTrailing
                                                    multiplier:1.0f
                                                      constant:0.f]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.titleLabel
                                                     attribute:NSLayoutAttributeBottom
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self.contentView
                                                     attribute:NSLayoutAttributeBottom
                                                    multiplier:1.f
                                                      constant:0.f]];
}

- (void)addBadgeLabel {
    [self.contentView addSubview:self.badgeLabel];
}

@end

#pragma mark - YCFunctionViewLayeout

@interface YCFunctionViewLayout()

/// 功能项数量
@property (nonatomic, assign) NSInteger numberOfItems;
/// 功能项大小
@property (nonatomic, assign) CGSize cellSize;

@end

@implementation YCFunctionViewLayout

#pragma mark - Layout

- (void)prepareLayout {
    [super prepareLayout];
    
    YCFunctionView *functionView = (YCFunctionView *)self.collectionView.superview;
    
    if ([functionView.dataSource respondsToSelector:@selector(numberOfCellsInFunctionView:)]) {
        self.numberOfItems = [functionView.dataSource numberOfCellsInFunctionView:functionView];
    } else {
        self.numberOfItems = 0;
    }
    
    if ([functionView.dataSource respondsToSelector:@selector(sizeOfCellInFunctionView:)]) {
        self.cellSize = [functionView.dataSource sizeOfCellInFunctionView:functionView];
    } else {
        self.cellSize = CGSizeMake(60.f, 80.f);
    }
}

- (CGSize)collectionViewContentSize {
    NSInteger numX = ((int)self.collectionView.frame.size.width)/self.cellSize.width;
    NSInteger numY = ((int)self.collectionView.frame.size.height)/self.cellSize.height;
    
    if (numX==0 || numY==0) {
        return CGSizeZero;
    }
    
    NSInteger page = self.numberOfItems%(numX * numY)!=0 ? self.numberOfItems/(numX * numY)+1 : self.numberOfItems/(numX * numY);
    
    YCFunctionView *functionView = (YCFunctionView *)self.collectionView.superview;
    functionView.pageControl.numberOfPages = page;
    
    return CGSizeMake(page*self.collectionView.frame.size.width, self.collectionView.frame.size.height);
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = self.collectionView.frame.size.width;
    CGFloat height = self.collectionView.frame.size.height;
    
    NSInteger numX = ((int)width)/self.cellSize.width;
    NSInteger numY = ((int)height)/self.cellSize.height;
    
    NSInteger curPage = indexPath.row / (numX * numY);
    NSInteger curIndexX = (indexPath.row % (numX * numY)) % numX;
    NSInteger curIndexY = (indexPath.row % (numX * numY)) / numX;
    
    CGFloat leftWidth = width - numX * self.cellSize.width;
    CGFloat leftHeight = height - numY * self.cellSize.height;
    
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    attributes.frame = CGRectMake(curPage*width+leftWidth/2+curIndexX*self.cellSize.width, leftHeight/2+curIndexY*self.cellSize.height, self.cellSize.width, self.cellSize.height);
    attributes.size = CGSizeMake(self.cellSize.width, self.cellSize.height);
    attributes.alpha = 1.0;
    attributes.center = CGPointMake(attributes.frame.origin.x + attributes.frame.size.width/2, attributes.frame.origin.y + attributes.frame.size.height/2);
    
    return attributes;
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (int i = 0; i < self.numberOfItems; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        [array addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
    }
    
    return array;
}

@end

#pragma mark - YCFunctionView

#define kCollectionViewCell @"cellFunction"

@interface YCFunctionView ()<UICollectionViewDataSource, UICollectionViewDelegate>

@end

@implementation YCFunctionView

#pragma mark - Life Cycle

- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (newSuperview) {
        [self addSubviews];
    }
    
    [super willMoveToSuperview:newSuperview];
}

#pragma mark - Setter and Getter

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:[[YCFunctionViewLayout alloc] init]];
        [_collectionView registerClass:[YCFunctionViewCell class] forCellWithReuseIdentifier:kCollectionViewCell];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.pagingEnabled = YES;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
    }
    
    return _collectionView;
}

- (UIPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] init];
        _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
        _pageControl.currentPageIndicatorTintColor = [UIColor grayColor];
        _pageControl.hidesForSinglePage = YES;
    }
    
    return _pageControl;
}

- (void)setDataSource:(id<YCFunctionViewDataSource>)dataSource {
    _dataSource = dataSource;

    [self.collectionView reloadData];
}

#pragma mark - View Config

/// 添加子视图
- (void)addSubviews {
    self.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self addCollectionView];
    [self addPageControl];
}

/// 添加集合视图
- (void)addCollectionView {
    self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self addSubview:self.collectionView];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView
                                                     attribute:NSLayoutAttributeTop
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self
                                                     attribute:NSLayoutAttributeTop
                                                    multiplier:1.0f
                                                      constant:0.f]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView
                                                     attribute:NSLayoutAttributeLeading
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self
                                                     attribute:NSLayoutAttributeLeading
                                                    multiplier:1.0f
                                                      constant:0.f]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView
                                                     attribute:NSLayoutAttributeTrailing
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self
                                                     attribute:NSLayoutAttributeTrailing
                                                    multiplier:1.0f
                                                      constant:0.f]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView
                                                     attribute:NSLayoutAttributeBottom
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self
                                                     attribute:NSLayoutAttributeBottom
                                                    multiplier:1.0f
                                                      constant:0.f]];
}

/// 添加分页指示器
- (void)addPageControl {
    self.pageControl.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self addSubview:self.pageControl];
    [self.pageControl addConstraint:[NSLayoutConstraint constraintWithItem:self.pageControl
                                                     attribute:NSLayoutAttributeHeight
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:nil
                                                     attribute:NSLayoutAttributeNotAnAttribute
                                                    multiplier:1.0f
                                                      constant:8.f]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.pageControl
                                                     attribute:NSLayoutAttributeLeading
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self
                                                     attribute:NSLayoutAttributeLeading
                                                    multiplier:1.0f
                                                      constant:0.f]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.pageControl
                                                     attribute:NSLayoutAttributeTrailing
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self
                                                     attribute:NSLayoutAttributeTrailing
                                                    multiplier:1.0f
                                                      constant:0.f]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.pageControl
                                                     attribute:NSLayoutAttributeBottom
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self
                                                     attribute:NSLayoutAttributeBottom
                                                    multiplier:1.0f
                                                      constant:0.f]];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self numberOfItems];
}

- (NSInteger)numberOfItems {
    NSInteger number = 0;
    
    if ([self.dataSource respondsToSelector:@selector(numberOfCellsInFunctionView:)]) {
        number = [self.dataSource numberOfCellsInFunctionView:self];
    }
    
    ((YCFunctionViewLayout *)self.collectionView.collectionViewLayout).numberOfItems = number;
    
    return number;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [self createCellInCollectionView:collectionView atIndexPath:indexPath];
}

- (YCFunctionViewCell *)createCellInCollectionView:(UICollectionView *)collectionView atIndexPath:(NSIndexPath *)indexPath {
    YCFunctionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollectionViewCell forIndexPath:indexPath];
    
    if ([self.dataSource respondsToSelector:@selector(functionView:configCell:atIndex:)]) {
        [self.dataSource functionView:self configCell:cell atIndex:indexPath.row];
    }
    
    return cell;
}

#pragma mark - UICollectionViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSInteger page = (NSInteger)(scrollView.contentOffset.x/self.pageControl.frame.size.width+0.5);
    self.pageControl.currentPage = page;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(functionView:didClickAtIndex:)]) {
        [self.delegate functionView:self didClickAtIndex:indexPath.row];
    }
}

@end
